package com.example.demo.aop;

import com.example.demo.annotation.Roles;
import com.example.demo.context.BaseContext;
import com.example.demo.service.UserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class AuthorizationAspect {
    @Autowired
    private UserRoleService userRoleService;
    @Around("@annotation(roles)")
    public Object around(ProceedingJoinPoint point, Roles roles) throws Throwable {
        String[] values = roles.values();
        boolean contains = false;
        for (String value : values) {
            log.info("value {}", value);
            if (value.equals(getRole())) {
                contains = true;
                break;
            }
        }
        if (contains) {
            log.info("用户id: " + BaseContext.getCurrentId() + "，用户角色: " + getRole());
            return point.proceed();
        } else {
            log.info("用户id: " + BaseContext.getCurrentId() + "，用户角色: " + getRole() + "，无权限");
            return new RuntimeException("没有权限");
        }
    }
    private String getRole() {
        Long id = userRoleService.getRoleByUserID(BaseContext.getCurrentId());
        if (id == 1) return "sa";
        else if (id == 2) return "da";
        else if (id == 3) return "ru";
        return null;
    }
}
